package demo.model;

import com.fasterxml.jackson.annotation.JsonIgnore;
import org.springframework.security.core.CredentialsContainer;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class JwtUser implements UserDetails, CredentialsContainer {
    private String username;
    private String name;
    @JsonIgnore
    private String password;

    private ArrayList<String> roles;

    public JwtUser() {

    }

    public JwtUser(String username, String name, String password, ArrayList<String> roles) {
        this.username = username;
        this.name = name;
        this.password = password;
        this.roles = new ArrayList<>(roles);
    }

    public JwtUser(JwtUser user) {
        this.username = user.username;
        this.name = user.name;
        this.password = user.password;
        this.roles = new ArrayList<>(user.roles);
    }

    public JwtUser(UserDetails user) {
        this.username = user.getUsername();
        this.name = this.username;
        this.password = user.getPassword();
        this.roles = user.getAuthorities()
                .stream().map(GrantedAuthority::getAuthority)
                .collect(Collectors.toCollection(ArrayList::new));
    }

    @Override
    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    @JsonIgnore
    public List<? extends GrantedAuthority> getAuthorities() {
        return roles.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
    }

    public ArrayList<String> getRoles() {
        return roles;
    }

    public void setRoles(ArrayList<String> roles) {
        this.roles = roles;
    }

    @JsonIgnore
    @Override
    public void eraseCredentials() {
        this.password = null;
    }

    @JsonIgnore
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @JsonIgnore
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @JsonIgnore
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @JsonIgnore
    @Override
    public boolean isEnabled() {
        return true;
    }
}
